package com.huiquan.answer.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huiquan.answer.dao.AnswerDao;
import com.huiquan.answer.domain.Answer;
import com.huiquan.answer.domain.AnswerVO;
import com.huiquan.answer.domain.DiseaseResult;
import com.huiquan.foundation.util.BusinessUtil;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.ReturnUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.*;

/**
 * @author lichao email:lichao@witspring.com
 * @Description:
 * @Date 2018/2/8 09:49
 * @since Ver V
 */
@Service
public class AnswerService extends BaseService {
    @Autowired
    private AnswerDao answerDao;

    public ModelAndView versionList(String startStr) {
        int start = startStr == null ? 1 : Integer.parseInt(startStr);
        // 初始化过滤的条件
        Map<String, Object> param = new HashMap<>();

        // 获取数据总量
        int totalSize = answerDao.selectAnswerVersionCount();

        // 获取翻页相关
        Map<String, Integer> pageNo = GetListUtil.getPageNoMap(totalSize, start);
        int startIndex = pageNo.get("startIndex");

        // 获取列表
        List<String> list = new ArrayList<>();
        if (startIndex < totalSize) {
            param.put("startIndex", startIndex);
            list = answerDao.selectAnswerVersionList(param);
        }

        Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, pageNo.get("start"), startIndex,
                pageNo.get("endPage"), list, null);
        return new ModelAndView("answer/index", map);
    }

    public ModelAndView answerList(String startStr, String version, String statusStr) {
        int start = startStr == null ? 1 : Integer.parseInt(startStr);
        int status = statusStr == null ? 1 : Integer.parseInt(statusStr);
        // 初始化过滤的条件
        Map<String, Object> param = new HashMap<>();
        param.put("version", version);
        param.put("status", status);

        // 获取数据总量
        int totalSize = answerDao.selectAnswerCount(param);

        // 获取翻页相关
        Map<String, Integer> pageNo = GetListUtil.getPageNoMap(totalSize, start);
        int startIndex = pageNo.get("startIndex");

        // 获取列表
        List<AnswerVO> list = new ArrayList<>();

        if (startIndex < totalSize) {
            param.put("startIndex", startIndex);
            list = transToVO(answerDao.selectAnswerList(param));
        }

        Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, pageNo.get("start"), startIndex,
                pageNo.get("endPage"), list, null);
        map.put("version", version);
        return new ModelAndView("answer/index", map);
    }

    public ReturnData answerCheckFlag(String id, String flag) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("flag", flag);
        // 更新answe的flag
        answerDao.updateFlag(params);
        // 根据id得到更新后的answer
        Answer answer = answerDao.selectAnswerById(Long.parseLong(id));
        // 判断answer是否存在于answerRepo
        if (answerDao.isExistWithAnswerRepo(answer)) {
            // 如果存在则根据当前answer更新answerRepo
            answerDao.updateAnswerRepo(answer);
        } else {
            // 如果不存在则插入answer到answerRepo
            answerDao.insertAnswerRepo(answer);
        }
        return ReturnUtil.success();
    }

    private List<AnswerVO> transToVO(List<Answer> answerList) {
        List<AnswerVO> resultList = new ArrayList<>();
        AnswerVO vo;
        for (Answer answer : answerList) {
            vo = new AnswerVO();
            vo.setId(answer.getId());
            vo.setAge(getAgeStr(answer.getAge()));
            vo.setGender(getGenderStr(answer.getGender()));
            vo.setSymptomMain(answer.getSymptomMain());
            vo.setSymptomOther(answer.getSymptomOther());
            vo.setDesc(getDescStr(answer.getDesc()));
            vo.setIndex(answer.getIndex());
            vo.setResult(getResultStr(answer.getResult()));
            vo.setFlag(answer.getFlag());
            resultList.add(vo);
        }
        return resultList;
    }

    /**
     * 年龄月份数转岁数字符串
     *
     * @param age
     * @return
     */
    private String getAgeStr(int age) {
        if (age <= 0) {
            return "0岁";
        }
        int year = age / 12;
        int month = age % 12;
        StringBuilder sb = new StringBuilder();
        if (year > 0) {
            sb.append(year).append("岁");
        }
        if (month > 0) {
            sb.append(month).append("个月");
        }
        return sb.toString();
    }

    /**
     * 得到性别字符
     *
     * @param gender
     * @return
     */
    private String getGenderStr(int gender) {
        if (gender == 1) {
            return "男";
        }
        if (gender == 2) {
            return "女";
        }
        return "未知";
    }

    private String getDescStr(String desc) {
        if ("-".equals(desc)) {
            return desc;
        }
        StringBuilder sb = new StringBuilder();
        JSONObject jsonObject = JSONObject.parseObject(desc);
        Set<String> keySet = jsonObject.keySet();
        for (String s : keySet) {
            sb.append(s).append(":");
            JSONObject temp = JSONObject.parseObject(jsonObject.get(s).toString());
            Set<String> tempSet = temp.keySet();
            String prefix = "";
            for (String s1 : tempSet) {
                sb.append(prefix).append(s1).append("=");
                JSONArray array = JSON.parseArray(temp.get(s1).toString());
                sb.append(array.toString());
                prefix = ",";
            }
            sb.append("\n");
        }
        return sb.toString();
    }

    private List<String> getResultStr(String result) {
        List<String> list = new ArrayList<>();
        JSONArray jsonArray = JSON.parseArray(result);
        for (Object object : jsonArray) {
            DiseaseResult diseaseResult = new DiseaseResult(object);
            list.add(diseaseResult.getDiseaseId().concat("\t").concat(diseaseResult.getDiseaseName()).concat("\t").concat(diseaseResult.getProbality()).concat("%"));
        }
        return list;
    }

    @Value("${answer.load_data.script}")
    private String loadDataScript;

    /**
     * 更新问答服务结果数据
     * @throws IOException
     */
    public void updateAnswerData() throws IOException {
        // 将181上数据拷贝并导入到临时表
        LOGGER.info("开始导入问答服务结果数据");
        BusinessUtil.excuteShell(new String[] { loadDataScript });
        LOGGER.info("导入问答服务结果数据完成");
        // 将临时表中数据导入到bas_answer
        answerDao.insertDataFromTemp();
        // 根据repo表更新bas_answer
        answerDao.updateDataByRepo();
    }
}
